<template>
  <div class="register_container">
    <el-row>
      <el-col :span="12" :xs="0"></el-col>
      <el-col :span="12" :xs="24">
        <el-form class="register_form" :model="registerForm" :rules="rules" ref="registerForms">
          <h1>欢迎注册</h1>
          <h2>请填写注册信息</h2>
          
          <!-- 用户名 -->
          <el-form-item prop="username">
            <el-input
              :prefix-icon="User"
              v-model="registerForm.username"
              placeholder="请输入用户名"
            ></el-input>
          </el-form-item>

          <!-- 密码 -->
          <el-form-item prop="password">
            <el-input
              type="password"
              :prefix-icon="Lock"
              v-model="registerForm.password"
              show-password
              placeholder="请输入密码"
            ></el-input>
          </el-form-item>

          <!-- 确认密码 -->
          <el-form-item prop="confirmPassword">
            <el-input
              type="password"
              :prefix-icon="Lock"
              v-model="registerForm.confirmPassword"
              show-password
              placeholder="请再次输入密码"
            ></el-input>
          </el-form-item>

          <el-form-item>
            <el-button :loading="loading" class="register_btn" type="primary" size="default" @click="register">
              注册
            </el-button>
          </el-form-item>

          <div class="to-login">
            已有账号？<el-link type="primary" @click="toLogin">去登录</el-link>
          </div>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { User, Lock } from '@element-plus/icons-vue'
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElNotification } from 'element-plus'

let registerForms = ref()
let $router = useRouter()
let loading = ref(false)
let registerForm = reactive({ 
  username: '',
  password: '',
  confirmPassword: ''
})

const toLogin = () => {
  $router.push('/')
}

const register = async () => {
  await registerForms.value.validate()
  
  if (registerForm.password !== registerForm.confirmPassword) {
    ElNotification({
      type: 'error',
      message: '两次输入的密码不一致'
    })
    return
  }

  loading.value = true
  try {
    const response = await fetch('/api/register', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        username: registerForm.username,
        password: registerForm.password
      })
    })
    
    const data = await response.json()
    
    if (data.code === 200) {
      ElNotification({
        type: 'success',
        message: data.message
      })
      $router.push('/')
    } else {
      ElNotification({
        type: 'error',
        message: data.message
      })
    }
  } catch (error) {
    ElNotification({
      type: 'error',
      message: '注册失败'
    })
  } finally {
    loading.value = false
  }
}

const validatePassword = (rule: any, value: string, callback: any) => {
  if (value.length < 6) {
    callback(new Error('密码长度至少6位'))
  } else {
    callback()
  }
}

const validateConfirmPassword = (rule: any, value: string, callback: any) => {
  if (value !== registerForm.password) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 5, max: 12, message: '用户名长度在5到12个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { validator: validatePassword, trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    { validator: validateConfirmPassword, trigger: 'blur' }
  ]
}
</script>

<style lang="scss" scoped>
.register_container {
  width: 100%;
  height: 100vh;
  background: url('@/assets/images/504.jpg') no-repeat;
  background-size: cover;
  
  .register_form {
    position: relative;
    width: 80%;
    top: 30vh;
    background: url('@/assets/images/OIP-C.jpg') no-repeat;
    background-size: cover;
    padding: 40px;
    
    h1 {
      color: black;
      font-size: 40px;
    }
    
    h2 {
      color: black;
      font-size: 20px;
      margin: 20px 0px;
    }
    
    .register_btn {
      width: 100%;
    }
    
    .to-login {
      text-align: center;
      margin-top: 20px;
      color: #666;
    }
  }
}
</style>
